import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { agencyAsync } from '@/appox/appox'
import { appoxUtility } from '@/appox/appox'

export const useVideoMonitorStore = defineStore('videoMonitor', () => {
  // 状态
  const channelList = ref([])
  const monitors = ref([])
  const isAppIdle = ref(true)
  const isUpdating = ref(false)

  // 计算属性
  const hasChannels = computed(() => channelList.value.length > 0)

  // 监听 monitors 变化并保存到 localStorage
  watch(monitors, (newMonitors) => {
    const channels = newMonitors.map(monitor => monitor.channelId)
    localStorage.setItem('AppoxJsTest.VideoMonitorChannels', JSON.stringify(channels))
  }, { deep: true })

  // 动作
  async function initializeVideoMonitor() {
    // 从 localStorage 加载保存的通道配置
    const savedChannels = localStorage.getItem('AppoxJsTest.VideoMonitorChannels')
    if (savedChannels) {
      try {
        const channels = JSON.parse(savedChannels)
        channels.forEach(channelId => {
          addMonitor(channelId)
        })
      } catch (error) {
        console.error('Failed to load saved channels:', error)
      }
    }
    
    await updateChannelList()
  }

  function generateDefaultChannelList() {
    return Array.from({ length: 24 }, (_, index) => ({
      id: `video@${index}`,
      title: String.fromCharCode(65 + index)
    }))
  }

  async function updateChannelList() {
    if (isUpdating.value) return
    
    try {
      isUpdating.value = true
      const channelTable = await agencyAsync.getChannelAliasTable()
      
      if (!channelTable) {
        channelList.value = generateDefaultChannelList()
        return
      }
      
      // 过滤并格式化视频通道
      channelList.value = Object.entries(channelTable)
        .filter(([id]) => {
          // 检查是否是video@0到video@23的通道
          const match = id.match(/^video@(\d+)$/)
          if (!match) return false
          const num = parseInt(match[1])
          return num >= 0 && num <= 23
        })
        .map(([id, info], index) => {
          // 将索引转换为字母 (0->A, 1->B, ...)
          const letter = String.fromCharCode(65 + index)
          return {
            id,
            title: `${letter}) ${info}`
          }
        })
        .sort((a, b) => {
          // 按通道号排序
          const numA = parseInt(a.id.split('@')[1])
          const numB = parseInt(b.id.split('@')[1])
          return numA - numB
        })
    } catch (error) {
      console.error('Failed to update channel list:', error)
      channelList.value = generateDefaultChannelList()
    } finally {
      isUpdating.value = false
    }
  }

  let idCount = 0

  function addMonitor(channelId = null) {
    const newMonitor = {
      id: idCount++,
      channelId: channelId || channelList.value[0]?.id || '',
      isRunning: false,
      imageData: null
    }
    monitors.value.push(newMonitor)
  }

  function removeMonitor(monitorId) {
    const index = monitors.value.findIndex(m => m.id === monitorId)
    if (index !== -1) {
      monitors.value.splice(index, 1)
    }
  }

  function updateChannel(monitorId, channelId) {
    const monitor = monitors.value.find(m => m.id === monitorId)
    if (monitor) {
      monitor.channelId = channelId
    }
  }

  function updateVideoImages() {
    // 遍历所有监控实例
    const interest = appoxUtility.getInterestTimeLocal()
    for (const monitor of monitors.value) {
      try {
        // 从channelId中提取通道号
        const match = monitor.channelId.match(/^video@(\d+)$/)
        if (!match) continue
        
        const channelNum = parseInt(match[1])
        if (channelNum < 0 || channelNum > 23) continue

        // 获取图像数据
        const imageWithInfo = appoxUtility.getPreviewJpegLocal(channelNum, interest, 1.0)
        if (imageWithInfo) {
          // 将Uint8Array转换为base64字符串
          const base64 = btoa(String.fromCharCode.apply(null, imageWithInfo[0]))
          monitor.imageData = `data:image/jpeg;base64,${base64}`
        }
      } catch (error) {
        console.error(`Failed to update image for monitor ${monitor.id}:`, error)
      }
    }
  }

  return {
    // 状态
    channelList,
    monitors,
    isAppIdle,
    isUpdating,
    // 计算属性
    hasChannels,
    // 动作
    initializeVideoMonitor,
    updateChannelList,
    addMonitor,
    removeMonitor,
    updateChannel,
    updateVideoImages
  }
}) 